<template>
  <!-- 调整项模板新增、编辑 -->
  <div class="ruleTemplate-data">
    <el-form :model="saveForm" ref="saveOrEditRef" label-width="160px" label-position="right" :rules="saveFormRules">
      <el-row>
        <el-col :span="10" :offset="2">
          <el-form-item label="调整项编号：" prop="adjCode" >
            <el-input v-model="saveForm.adjCode" maxlength="32" :disabled="operateType==2 || operateType == 3"/>
          </el-form-item>
        </el-col>
      <el-col :span="10" >
          <el-form-item label="调整项名称：" prop="adjName">
            <el-input v-model="saveForm.adjName" maxlength="200" :disabled="operateType == 3"/>
          </el-form-item>
        </el-col>  
      </el-row>
       
      <el-row>
        <el-col :span="10" :offset="2">
          <el-form-item label="调整类型：" prop="adjType">
            <el-select v-model="saveForm.adjType" placeholder="请选择" :disabled="operateType == 3">
              <el-option v-for="item in adjTypeList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" >
          <el-form-item label="计算方式：" prop="countWay">
            <el-select v-model="saveForm.countWay" placeholder="请选择"  :disabled="operateType == 3"  @change="countWayChange">
                  <el-option v-for="item in countWayList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10" :offset="2">
          <el-form-item label="追踪数据类型：" prop="trackDateType">
            <el-select v-model="saveForm.trackDateType" placeholder="请选择"  :disabled="operateType == 3">
              <el-option v-for="item in trackDateTypeList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" >
          <el-form-item label="字段序号：" prop="seqNum">
            <el-select v-model="saveForm.seqNum" placeholder="请选择"   :disabled="operateType == 3">
                  <el-option v-for="item in seqNumList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10" :offset="2">
          <el-form-item label="插值方式：" prop="insertWay" >
            <el-select v-model="saveForm.insertWay" placeholder="请选择" :disabled="operateType == 3">
              <el-option v-for="item in insertWayList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10" :offset="2">
          <el-form-item label="是否BreakFund纳入项：" prop="fundingFlag" >
            <el-select v-model="saveForm.fundingFlag" placeholder="请选择" :disabled="operateType == 3">
              <el-option v-for="item in fundingFlagList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" >
          <el-form-item label="是否利差锁定项：" prop="lockDiffFlag">
            <el-select v-model="saveForm.lockDiffFlag" placeholder="请选择"  :disabled="operateType == 3 || saveForm.countWay =='4'">
              <el-option v-for="item in lockDiffFlagList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <el-row class="container">
      <el-col style="margin-right:10px;" class="content-left">
        <upper-template :searchIcon="false" :configIcon="false">
           <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addOrEditModelFunc('1')" v-if="operateType != 3">新增</el-button>
            <el-button @click="addOrEditModelFunc('2')" v-if="operateType != 3">编辑</el-button>
            <el-button @click="delModelFunc()" v-if="operateType != 3">删除</el-button>
          </template>
        </upper-template>
        <el-table
          ref="multipleModelTable"
          :data="tableModelData"
          style="width: 100%"
          @row-click="authorizeModelFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="elementFieldName"
            label="业务元素"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="caliberFlag"
            label="是否使用口径"
            :show-overflow-tooltip="true"
            :formatter="row => (row.caliberFlag == 1 ? '是' : '否')"
          ></el-table-column>
          <el-table-column
            prop="caliberGroupCode"
            label="口径组"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="fieldNum"
            label="顺序号"
            :show-overflow-tooltip="true"
          ></el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog
      v-dialogDrag
      :title="titleModelName"
      :visible.sync="ruleTemplateFieldDi"
      :append-to-body="true"
      width="30%"
      height="500"
      top="2%"
    >
      <div style="height:200px">
      <el-form
        :model="saveFieldForm"
        ref="saveOrEditFieldRef"
        label-width="110px"
        label-position="left"
        :rules="saveFieldFormRules"
      >
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="业务元素：" prop="elementField">
            <table-select 
               ref="fieldSelect"
               :data="tableElementFieldDataBasic"
               v-model="saveFieldForm.elementField"
               fieldCode='elementField'
               fieldName='elementName'
               :tableHead ="[{prop:'elementField',label:'元素字段'},{prop:'elementName',label:'元素名称'},]"
               @change="selectCaliberGroup()"
               ></table-select>
 
            </el-form-item>
          </el-col>
          <el-col :span="18" :offset="3">
            <el-form-item label="是否使用口径：" prop="caliberFlag">
              <el-select v-model="saveFieldForm.caliberFlag" placeholder="请选择" style="width:100%" @change="caliberFlagChange">
                <el-option
                  v-for="item in caliberFlags"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" :offset="3" v-if="caliberGroupDi">
            <el-form-item label="口径方案：" prop="caliberGroupCode" >
              <table-select 
               ref="caliberSelect"
               :data="tableCaliberGroupDataBasic"
               v-model.trim="saveFieldForm.caliberGroupCode"
               fieldCode='caliberProjectCode'
               fieldName='caliberProjectName'
               :tableHead ="[{prop:'caliberProjectCode',label:'口径编码'},{prop:'caliberProjectName',label:'口径名称'},]"
               ></table-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" :offset="3">
            <el-form-item label="顺序号：" prop="fieldNum">
              <el-input
                v-model.trim="saveFieldForm.fieldNum"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      </div>
      <div slot="footer">
        <el-button @click="saveFieldFun">确 定</el-button>
        <el-button @click="ruleTemplateFieldDi = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ruleTemplate,adjRule } from "@/api/index";
import tableSelect from "@/components/ftp/tableSelect";
import { getDict } from "@/api/getDict";
export default {
  data() {
    return {

      adjTypeList: [],
      countWayList:[],//动态方法取值？？？
      trackDateTypeList:[],
      seqNumList:[],
      insertWayList:[],
      fundingFlagList:[],
      lockDiffFlagList:[],

      //规则字段实体
      saveFieldForm: {
        caliberFlag: "0",
        elementField: "",
        caliberGroupCode: "",
        elementFieldName: "",
        fieldNum: ""
      },
      //表单字段规则校验
      saveFormRules: {
        adjCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]{1,40}$/,
            message: "只可输入(1-40)位的英文字母、数字和下划线！",
            trigger: "blur"
          },
          { validator: this.templateCodeValid, trigger: "blur" }
        ],
        adjName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,100}$/,
            message: "只可输入1-100位英文数字汉字和_",
            trigger: "blur"
          },
          { validator: this.templateNameValid, trigger: "blur" }
        ],
        adjType: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        countWay: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        seqNum: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { validator: this.seqNumValid, trigger: "blur" }
        ],
        insertWay: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        fundingFlag: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        lockDiffFlag: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        trackDateType: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ]

      },
      saveFieldFormRules: {
        elementField: [
          { required: true, message: "该输入项为必输项", trigger: "change" },
          { validator: this.elementFieldValid, trigger: "blur" }
        ],
        caliberFlag: [
          { required: true, message: "该输入项为必输项", trigger: "change" }
        ],
        caliberGroupCode: [
          { required: true, message: "该输入项为必输项", trigger: "change" }
        ],
        fieldNum: [
          { required: true, message: "该输入项为必输项", trigger: "change" },
          {
            pattern: /^[0-9]{1,9}$/,
            message: "最多只可输入9位数字！",
            trigger: "blur"
          },
          { validator: this.fieldNumValid, trigger: "blur" }
        ]
      },
      //规则字段列表数据
      tableModelData: [],
      //是否使用口径字典
      caliberFlags: [],
      //定价方法规则字段弹窗标识
      ruleTemplateFieldDi: false,
      titleModelName: "",
      //业务元素悬浮框
      elementFieldContent : false,
      //业务元素列表初始
      tableElementFieldDataBasic: [],
      //业务元素列表
      tableElementFieldData: [],
      //口径方案悬浮框
      caliberGroupContent : false,
      //口径方案初始列表
      tableCaliberGroupDataBasic: [],
      //口径方案列表
      tableCaliberGroupData: [],
      //口径方案标识
      caliberGroupDi: false,
      //模板字段操作状态
      fieldOperateType: 1,
      //编辑业务元素
      elementFieldOld: "",
      //编辑顺序号
      fieldNumOld: "",
      //编辑的模板元素
      savaFieldFormOld: {},
      //编辑模板名称
      adjNameOld: "",
      seqNumOld: "",
      elementField:"",
      elementName:"",
    };
  },
  props: {
    saveForm: {
      type: Object,
      default: ()=>({})
    },
    operateType: {
      type: String,
      default: ""
    }
  },
  watch: {
    
  },
  components: {
    tableSelect
  },
  created() {
    this.getCaliberFlagDict();
    this.getAdjTypeListDict();
    this.getTrackDateTypeListDict();
    this.getCountWayListDict();
    this.getSeqNumListDict();
    this.getInsertWayListDict();
    this.getFundingFlagListDict();
    this.getLockDiffFlagListDict();
    this.elementFieldDataSelect();
  },
  computed: {
    
  },
  mounted() {
   
  },
  inject:['closeRuleTemplateDi'],
  methods: {
     
    //计算方式=4 时，是否利差锁定项=1
    countWayChange() {
      if(this.saveForm.countWay=='4'){
          this.saveForm.lockDiffFlag='1';
      } 
    },
    //顺序号验证
    fieldNumValid(rule, value, callback){
      let index = 0;
      this.tableModelData.forEach(item=>{
        if(value == item.fieldNum) {
          if(this.fieldOperateType == "1") {
            index = 1;
            callback(new Error("调整项字段序号已存在，无法使用！"));
          } else {
            if (this.fieldNumOld != value) {
              index = 1;
              callback(new Error("调整项字段序号已存在，无法使用！"));
            }
          }
        }
      });
      if(index == 0) {
        callback();
      }
    },
    //业务元素验证
    elementFieldValid(rule, value, callback){
      let index = 0;
      this.tableModelData.forEach(item=>{
        if(value === item.elementField) {
          if(this.fieldOperateType == "1") {
            index = 1;
            callback(new Error("此业务元素已存在，无法使用！"));
          } else {
            if (this.elementFieldOld != value) {
              index = 1;
              callback(new Error("此业务元素已存在，无法使用！"));
            }
          }
        }
      });
      if(index == 0) {
        callback();
      }
    },
    //模板编号验证
    templateCodeValid(rule, value, callback){
      if(this.operateType == "1") {
        let data = {
          validateParam: "adjCode:"+value
        };
        adjRule.checkUsing(data).then(res => {
          if (res.code === 200) {
            if(res.data != "false") {
              callback(new Error("调整项编号已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //模板名称验证
    templateNameValid(rule, value, callback){
      if(this.operateType == "1" ||(this.operateType == "2"&&this.adjNameOld != value)) {
        let data = {
          validateParam: "adjName:"+value
        };
        adjRule.checkUsing(data).then(res => {
          if (res.code === 200) {
            if(res.data != "false") {
              callback(new Error("调整项名称已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    seqNumValid(rule, value, callback){
      if(this.operateType == "1" ||(this.operateType == "2" && this.seqNumOld != value)) {
        let data = {
          validateParam: "seqNum:"+value
        };
        adjRule.checkUsing(data).then(res => {
          if (res.code === 200) {
            if(res.data != "false") {
              callback(new Error("调整项字段序号已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //保存按钮
    saveAdjTemplate() {
      this.$refs["saveOrEditRef"].validate(valid => {
        if(valid) {

          let length = this.tableModelData.length;
          if(length == 0) {
            this.$message.warning("请新增规则字段信息");
            return false;
          } else {
            //规则字段
            let orgTermFlag = false;
            for(let key in this.tableModelData){
              if(this.tableModelData[key].elementField=='term'){
                orgTermFlag = true;
              }
            }
            if(this.saveForm.insertWay=='2' && !orgTermFlag){
              this.$message.warning("插值方式为线性插值时,规则字段中必须有原始期限！");
              return false;
            }

            this.saveForm.ruleTemplate.ruleTemplateFields = this.tableModelData;
            
            let data = {
              operateType: this.operateType,
              adjustDefinition: this.$clone(this.saveForm)
            };
            ruleTemplate.saveAdjDef(data).then(res => {
              if (res.code == 200) {
                this.$message.success("保存成功");
                this.$emit("backReSearch");
                this.closeRuleTemplateDi();
                return true;
              } else {
                this.$message.error(res.message || "保存失败");
                return false;
              }
            });
          }
        }
      });
    },
    //是否使用口径选择
    caliberFlagChange(val) {
      if(val === "1") {
        //使用口径，显示口径方案选择
        this.caliberGroupDi = true;
      } else {
        this.caliberGroupDi = false;
      }
    },
    //业务元素实时检索
    searchElementField() {
      let search = this.saveFieldForm.elementFieldName;
      this.tableElementFieldData = [];
      this.tableElementFieldDataBasic.filter(item=>{
        if(item.elementName.indexOf(search) != -1||item.elementField.indexOf(search) != -1) {
          this.tableElementFieldData.push(item);
        }
      });
      if(!this.elementFieldContent) {
        this.elementFieldContent = true;
      }
    },
    //业务元素选择
    selectElementField () {
      this.tableElementFieldData = JSON.parse(JSON.stringify(this.tableElementFieldDataBasic));
    },
    elementFieldDataSelect () {
      let data = {
        pricingFlag: 1,
        nopage: true
      }
      ruleTemplate.findBusinessByType(data).then(res => {
        if (res.code === 200) {
          this.tableElementFieldDataBasic = res.rows;
        }
      });
    },
    authorizeElementFieldFor(row){
      this.saveFieldForm.elementField = row.elementField;
      this.saveFieldForm.elementFieldName = row.elementName;
      this.elementFieldContent = false;
    },
    searchCaliberGroup() {
      let search = this.saveFieldForm.caliberGroupCode;
      this.tableCaliberGroupData = [];
      this.tableCaliberGroupDataBasic.filter(item=>{
        if(item.elementName.indexOf(search) != -1||item.elementField.indexOf(search) != -1) {
          this.tableCaliberGroupData.push(item);
        }
      });
      if(!this.elementFieldContent) {
        this.elementFieldContent = true;
      }
    },
  
     selectCaliberGroup () {
      if (this.saveFieldForm.elementField != null&&this.saveFieldForm.elementField != '') {
        let data = {
          templateFieldId: this.saveFieldForm.elementField
        }
        ruleTemplate.findCaliberByTemplateFieldId(data).then(res => {
          if (res.code === 200) {
            this.tableCaliberGroupDataBasic = res.datas;
          }
        });
      } else {
        this.tableElementFieldData = [];
      }
      this.saveFieldForm.caliberGroupCode='';
      this.saveFieldForm.caliberFlag='0';
      this.caliberFlagChange('0')
    },
    authorizeCaliberGroupFor(row){
      this.saveFieldForm.caliberGroupCode = row.caliberProjectCode;
      this.caliberGroupContent = false;
    },
    //查询
    searchModelFunc() {

      if(this.operateType == "2") {
          this.adjNameOld = this.saveForm.adjName;
          this.seqNumOld = this.saveForm.seqNum;
      }
      
      if(this.saveForm.adjId != null && this.saveForm.adjId != "") {
        let data = {templateId:this.saveForm.adjId};
        ruleTemplate.findAllRuleTemplateField(data).then(res => {
          if (res.code === 200) {
            this.tableModelData = res.datas;
          }
        });
      } else {
         for(let k in this.saveForm){
           if(k!=='ruleTemplate') this.saveForm[k] =""
          }
          this.saveForm.ruleTemplate= {
              ruleTemplateFields:[]
          }	
          this.saveForm.fundingFlag = "0";
          this.saveForm.lockDiffFlag = "0";
          this.tableModelData = [];
      }
    },
    //字典信息
    getCaliberFlagDict() {
      getDict("ftp_boolean_bork").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.caliberFlags = res.datas;
          }
        }
      });
      
    },
    getAdjTypeListDict() {
      getDict("ftp_adj_type").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.adjTypeList = res.datas;
          }
        }
      });
    },
    getCountWayListDict() {
      getDict("ftp_count_way").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.countWayList = res.datas;
          }
        }
      });
    },
     getTrackDateTypeListDict() {
      getDict("ftp_cp_track_date_cd").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.trackDateTypeList = res.datas;
          }
        }
      });
    },
    getSeqNumListDict() {
      getDict("ftp_seq_num").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.seqNumList = res.datas;
          }
        }
      });
    },
    getInsertWayListDict() {
      getDict("ftp_insert_way").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.insertWayList = res.datas;
          }
        }
      });
    },
    getFundingFlagListDict() {
      getDict("ftp_funding_flag").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.fundingFlagList = res.datas;
          }
        }
      });
    },
    getLockDiffFlagListDict() {
      getDict("ftp_lock_diff_flag").then(res => {
        if (res.code == 200) {
          if (res.datas != "" && null != res.datas) {
            this.lockDiffFlagList = res.datas;
          }
        }
      });
    },


    //新增、编辑规则字段
    addOrEditModelFunc(val) {
      this.ruleTemplateFieldDi = true;
      this.fieldOperateType = val;
      if(this.$refs.saveOrEditFieldRef) {
        this.$refs.saveOrEditFieldRef.resetFields();
      }
      if(val === "1") {
        this.titleModelName = "添加调整项定义规则字段信息";
        this.caliberGroupDi = false;
        this.saveFieldForm.caliberFlag= "0";
        this.saveFieldForm.elementField= "";
        this.saveFieldForm.caliberGroupCode= "";
        this.saveFieldForm.caliberGroupName= "";
        this.saveFieldForm.elementFieldName= "";
        this.saveFieldForm.fieldNum= "";
       
      } else {
        this.titleModelName = "编辑调整项定义规则字段信息";
        let selection = this.$refs.multipleModelTable.selection; 
        this.saveFieldForm = {...selection[0]};
        this.savaFieldFormOld = selection[0];
        this.elementFieldOld = selection[0].elementField;
        
        this.fieldNumOld = selection[0].fieldNum;
        if(selection[0].caliberFlag==0) {
          this.caliberGroupDi = false;
        } else {
          this.caliberGroupDi = true;
        }
      }
      
    },
    //保存规则字段
    saveFieldFun () {
      this.$refs["saveOrEditFieldRef"].validate(valid => {
        if (valid) {
           this.saveFieldForm.elementFieldName=this.$refs.fieldSelect.name;
           this.saveFieldForm.caliberGroupName=this.$refs.caliberSelect?this.$refs.caliberSelect.name:"";
          let data = {...this.saveFieldForm};
          if(this.fieldOperateType === "1") {
            this.tableModelData.push(data);
          } else {
            this.tableModelData.splice(this.tableModelData.indexOf(this.savaFieldFormOld),1,data);
          }
          this.ruleTemplateFieldDi = false;
        }
      });
    },
    //删除规则字段
    delModelFunc() {
      let selection = this.$refs.multipleModelTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的规则模板字段数据");
      }
      this.$confirm("您确定要删除选中规则模板字段吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          selection.forEach(item=>{
            this.tableModelData.splice(this.tableModelData.indexOf(item),1);
          });
        })
        .catch((e) => {
          console.log(e)
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //点击行选中
    authorizeModelFor(row) {
      if (this.$refs.multipleModelTable) {
          this.$refs.multipleModelTable.clearSelection()
      }
      this.$refs.multipleModelTable.toggleRowSelection(row, true)
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
.selectBox {
  background: url("~@/assets/images/select_btn.gif");
  background-repeat: no-repeat;
  height: 26px;
  width: 23px;
  position: absolute;
  right: 0;
  top: 5px;
  cursor: pointer;
}
/deep/.el-popover {
  max-height: 160px;
  overflow: auto;
}
</style>
